/*
 * @Description: 请描述此文件
 * @Author: LDM
 * @Date: 2021-09-16 18:18:38
 * @LastEditors: LDM
 * @LastEditTime: 2021-10-27 15:44:33
 */
import type {
  Router,
  RouteLocationNormalized,
  NavigationGuardNext,
  RouteRecordRaw
} from 'vue-router'
import { markRaw } from 'vue'
import NProgress from 'nprogress'
import { useUserStoreWithOut, usePermisionnStoreWithOut } from '/@/store'
let router: Router

const whiteList: string[] = ['/login', '/error/404', '/error/401']

NProgress.configure({ showSpinner: false })
async function beforeRouteEachHandler(
  this: Router,
  to: RouteLocationNormalized,
  from: RouteLocationNormalized,
  next: NavigationGuardNext
) {
  const userStore = useUserStoreWithOut()
  const permissionStore = usePermisionnStoreWithOut()
  NProgress.start()
  if (!this.hasRoute(to.name as string)) {
    if (!to.name)
      console.warn(`%c 🍯 ${to.path}:  该路径没有设置route.name属性,所以无法进行跳转。请先创建`)
    console.log(from.name)
    return next({ path: '/error/401', replace: true })
  }

  // Determine whether the user has logged in
  if (userStore.$state.token) {
    if (to.path === '/login') {
      // If is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      // // 如果取消权限验证
      if (!permissionStore.$state.roleCheck) {
        permissionStore.UpdatePermissionRoutes([])
        return next()
      }
      // Check whether the user has obtained his permission roles
      if (userStore.$state.roles.length === 0) {
        try {
          await userStore.GetUserInfoAction()
          const roles = userStore.$state.roles
          // Generate accessible routes map based on role
          permissionStore.UpdatePermissionRoutes(roles)
          // Dynamically add accessible routes
          permissionStore.$state.routes.forEach((route) => {
            router.addRoute(markRaw({ ...route }) as unknown as RouteRecordRaw)
          })
          // Hack: ensure addRoutes is complete
          // Set the replace: true, so the navigation will not leave a history record
          /* 如果请求后,roles还是0,直接next就行,不用replace(不然导致死循环) */
          roles.length === 0 ? next() : next({ ...to, replace: true })
        } catch (err) {
          // Remove token and redirect to login page
          alert('获取用户信息失败')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      } else {
        next()
      }
    }
  } else {
    // Has no token
    if (whiteList.indexOf(to.path) !== -1) {
      // In the free login whitelist, go directly
      next()
    } else {
      // Other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }

  // next()
}
function afterRouteEachHandler(to: any) {
  NProgress.done()
  document.title = to.meta.title
}
export function setupPermissionGuard(_router: Router) {
  router = _router
  router.beforeEach((...args) => beforeRouteEachHandler.apply(_router, args))
  router.afterEach((to) => afterRouteEachHandler.apply(_router, [to]))
}
